package com.ww.springboot.boot.algorithm.leetcode1;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-04-20 09:32
 */
public class BR112路径总和 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);

        System.out.println(hasPathSum(root, 3));
    }

    /**
     * 先序遍历 遇到叶子节点时求和
     * <p>
     * 如果主节点没有 只有一个分支 则单个主节点不算路径
     *
     * @param root
     * @param targetSum
     * @return
     */
    public static boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        return getChild(root, targetSum);
    }

    public static boolean getChild(TreeNode root, int targetSum) {
        if(root.left == null && root.right == null){
            if(targetSum == root.val){
                return true;
            }
        }else {
            if (root.left != null) {
                boolean flag = getChild(root.left, targetSum - root.val);
                if (flag == true) {
                    return true;
                }
            }
            if (root.right != null) {
                boolean flag = getChild(root.right, targetSum - root.val);
                if (flag == true) {
                    return true;
                }
            }
        }
        return false;
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
